package com.cxx.purchasecharge.dal.impl;

import java.util.List;

import javax.persistence.Query;

import org.apache.commons.collections.CollectionUtils;

import com.cxx.purchasecharge.core.model.persistence.Authority;
import com.cxx.purchasecharge.dal.AuthorityDao;
import com.cxx.purchasecharge.dal.common.MyGenericDaoImpl;

public class AuthorityDaoImpl extends MyGenericDaoImpl<Authority, Long> implements AuthorityDao {

	public AuthorityDaoImpl() {
		super(Authority.class);
	}

	@Override
	public Authority findByName(String name) {
		String sql = "select a from Authority a where a.name=?1";
		Query query = getEntityManager ().createQuery (sql, Authority.class);
		query.setParameter (1, name);
		return CollectionUtils.isNotEmpty (query.getResultList ()) ? (Authority)query.getResultList ().get (0) : null;
	}

	@Override
	public boolean isSystem(String name) {
		String sql = "select a.system from Authority a where a.name=?1";
		Query query = getEntityManager ().createQuery (sql);
		query.setParameter (1, name);
		if(CollectionUtils.isNotEmpty (query.getResultList ()) && query.getResultList ().get (0) != null) 
		{
		    return Boolean.parseBoolean (query.getResultList ().get (0).toString ());
		}
		return false;
	}

	@Override
	public List<Authority> findByParent(Long parentId) {
		String sql = "select a from Authority a where a.parent.id=?1";
		Query query = getEntityManager ().createQuery (sql, Authority.class);
		query.setParameter (1, parentId);
		return query.getResultList ();
	}

}
